package utils

import (
	"context"
	"github.com/go-redis/redis/v8"
	"time"
)

// RedisClient 结构体包含了一个Redis客户端
type RedisClient struct {
	Client *redis.Client
}

// NewRedisClient 初始化一个新的Redis连接池
func NewRedisClient(addr string, password string, db int) *RedisClient {
	rdb := redis.NewClient(&redis.Options{
		Addr:     addr,     // Redis地址
		Password: password, // 密码
		DB:       db,       // 默认数据库
	})

	return &RedisClient{Client: rdb}
}

// TryLock 尝试获取一个分布式锁
func (c *RedisClient) TryLock(ctx context.Context, key string, value string, expiration time.Duration) (bool, error) {
	// SET命令的参数
	result, err := c.Client.SetNX(ctx, key, value, expiration).Result()
	if err != nil {
		return false, err
	}
	return result, nil
}

// Unlock 释放一个分布式锁
func (c *RedisClient) Unlock(ctx context.Context, key string) error {
	_, err := c.Client.Del(ctx, key).Result()
	return err
}

//使用分布式锁
//func main() {
//	client := NewRedisClient("localhost:6379", "", 0)
//	defer client.Client.Close()
//
//	ctx := context.Background()
//
//	// 尝试获取锁
//	locked, err := client.TryLock(ctx, "my-lock", "unique-value", 10*time.Second)
//	if err != nil {
//		fmt.Println("Failed to acquire lock:", err)
//		return
//	}
//	if locked {
//		fmt.Println("Lock acquired")
//		// 业务逻辑
//		// ...
//
//		// 释放锁
//		if err := client.Unlock(ctx, "my-lock"); err != nil {
//			fmt.Println("Failed to release lock:", err)
//			return
//		}
//		fmt.Println("Lock released")
//	} else {
//		fmt.Println("Lock is already acquired by someone else")
//	}
//}
